<?php
namespace app\index\controller\dictionary;
use app\index\controller\BaseIndex;
use szktor\ClinicDict; //诊所门店公共字典
use app\common\model\ClinicDictsheet; //字典表数据

/*
* 前台-字典维护 -> 业务字典
* index/dictionary.yewuzd/index
*/
class Yewuzd extends BaseIndex
{
    protected $noNeedLogin = [];  //无需登录的方法，同时也就不需要鉴权了
    protected $noNeedRight = ['info','del','load_clinic_zsdly','save_clinic_zsdly']; //无需鉴权的方法，但需要登录

    //首页
    public function index()
    {
        if($this->request->isPost() || $this->request->isAjax())
        {
            try
            {
                $data = $this->request->only(['dicttype','keyword','status','page'],'post');
                if(!isset($data['dicttype']))
                {
                    return json(['code' => '1', 'msg' => '参数错误，无法获取数据', 'count' => '0', 'data' => []]);
                }
                $data['dicttype'] = strtolower($data['dicttype']);
                //字典表数据_通用 获取列表
                return $this->dictSheetList($data);
            }catch (\think\Exception $e){ // use think\Exception;
               return json(['err' => '500', 'msg' => '错误：' . $e->getMessage()]);
            }
        }
		$this->assign([
            'ywzd_list' => ClinicDict::getClinicYeWuDictList(), //业务字典列表
            'fbmx_fbtype_list' => ClinicDict::getClinicFeiBieTypeList(), //费别明细 列表  下的 费别类型
        ]);
        return $this->view->fetch();
    }
    //修改 + 新增
    public function info()
    {
        if(!$this->request->isAjax())
        {
            return json(['err' => '1', 'msg' => '对不起，您的访问方式有误']);
        }
        try
        {
            $data = $this->request->only(['dicttype'],'post');
            if(!isset($data['dicttype']))
            {
                return json(['err' => '1', 'msg' => '参数错误，无法执行']);
            }
            //字典表数据_通用--修改 + 新增
            return $this->clinicDictsheetInfo();
        }catch (\think\Exception $e){ // use think\Exception;
           return json(['err' => '500', 'msg' => '错误：' . $e->getMessage()]);
        }
    }
    //删除
    public function del()
    {
        if(!$this->request->isAjax())
        {
            return json(['err' => '1', 'msg' => '对不起，您的访问方式有误']);
        }
        try
        {
            $data = $this->request->only(['dicttype','id'],'post');
            if(!isset($data['dicttype']))
            {
                return json(['err' => '1', 'msg' => '参数错误，无法执行']);
            }
            $r = false;
            $map = [['id','in',$data['id']],['clinic_id','=',$this->admin['clinic_id']]];
            //字典表数据_通用
            $r = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_dictsheet')->where($map)->delete();
            if(!$r) return json(['err' => '2', 'msg' => '删除失败，请重试']);
            return json(['err' => '0', 'msg' => '删除成功']);
        }catch (\think\Exception $e){ // use think\Exception;
           return json(['err' => '500', 'msg' => '错误：' . $e->getMessage()]);
        }
    }

    //字典表数据列表_通用
    private function dictSheetList($post)
    {
        //条件
        $map = [['clinic_id','=', $this->admin['clinic_id']]];
        $page = isset($post['page']) ? $post['page'] : 1;
        if(isset($post['dicttype']) && $post['dicttype'] != '')
        {
            if(strtolower($post['dicttype']) != 'all') $map[] = ['type','=',strtolower($post['dicttype'])];
        }
        if(isset($post['keyword']) && $post['keyword'] != '')
        {
            $map[] = ['name|py_code|wb_code','like','%' . $post['keyword'] . '%'];
        }
        if(isset($post['status']) && $post['status'] != '')
        {
            if(strtoupper($post['status']) != 'ALL') $map[] = ['status','=',(int)$post['status']];
        }
        $limit = intval($this->pageNum) > 0 ? intval($this->pageNum) : 20;
        $list = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_dictsheet')->where($map)->field('*')
                ->order('sort desc')->paginate($limit,false,['page' => $page, 'var_page' => 'page']);
        if (count($list) <= 0) {
            return json(['code' => '1', 'msg' => '当前页下的数据已显示完毕！', 'count' => '0', 'data' => []]);
        }
        $res = ['code' => 0,'msg' => '', 'count' => $list->total(), 'data' => $list->items()];
        foreach ($res['data'] as $key => &$val) {
            if($val['type'] == 'fbmx')
            {
                //费别明细 列表  下的 费别类型
                $val['other_val_txt'] = _getDictNameTxt($val['other_val'],ClinicDict::getClinicFeiBieTypeList());
            }
            $val['create_time'] = $val['create_time'] > 0 ? date('Y-m-d Hi:s') : '';
        }
        return json($res);
    }

    //字典表数据_通用--修改+新增
    private function clinicDictsheetInfo()
    {
        $data = $this->request->only([
            'dicttype','id','name','other_val','other_val_two','py_code','wb_code','sort','status',
        ],'post');
        if(!isset($data['id']))
        {
            return json(['err' => '1', 'msg' => '参数错误，无法执行']);
        }
        $dictType = strtolower($data['dicttype']);
        if(!isset($data['name']) || $data['name'] == '')
        {
            return json(['err' => '2', 'msg' => '必须输入一个名称']);
        }
        if($dictType == 'zffs')
        {
            if(!isset($data['other_val']) || $data['other_val'] == '')
            {
                return json(['err' => '4', 'msg' => '请输入支付方式编号']);
            }
        }
        try
        {
            $info = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_dictsheet')->where(['id' => intval($data['id']), 'clinic_id' => $this->admin['clinic_id']])->find();
            $sqlData = [
                'clinic_id' => $this->admin['clinic_id'], //诊所门店表的id
                'type' => $dictType, //字典类型
                'name' => $data['name'], //中文名称
                'other_val' => isset($data['other_val']) ? $data['other_val'] : '', //其它数值1
                'other_val_two' => isset($data['other_val_two']) ? $data['other_val_two'] : '', //其它数值2
                'py_code' => isset($data['py_code']) ? $data['py_code'] : '', //拼音码助记词
                'wb_code' => isset($data['wb_code']) ? $data['wb_code'] : '', //五笔码助记词
                'sort' => isset($data['sort']) ? $data['sort'] : '0', //排序
                'status' => isset($data['status']) ? (int)$data['status'] : '1', //状态1.启用,0停用
                'ext_json' => '', //扩展json参数
                'create_time' => time(), //创建时间
            ];
            if($info) //数据已存在
            {
                unset($sqlData['clinic_id'],$sqlData['type'],$sqlData['create_time']);
                $editRes = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_dictsheet')->where(['id' => $info['id']])->update($sqlData);
            }else{ //数据不存在
                $editRes = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_dictsheet')->insertGetId($sqlData);
            }
            unset($info,$sqlData);
            if(!$editRes) return json(['err' => '2', 'msg' => '字典数据保存失败']);
            return json(['err' => '0', 'msg' => '字典数据已保存成功']);
        }catch (\think\Exception $e){ // use think\Exception;
           return json(['err' => '500', 'msg' => '失败：' . $e->getMessage()]);
        }
    }
    //加载诊所已设置的注射单来源
    public function load_clinic_zsdly()
    {
        if(!$this->request->isAjax())
        {
            return json(['err' => '1', 'msg' => '对不起，您的访问方式有误']);
        }
        try
        {
            $data = $this->request->only(['dicttype'],'post');
            if(!isset($data['dicttype']) || $data['dicttype'] != 'zsdly')
            {
                return json(['err' => '1', 'msg' => '参数错误，无法执行']);
            }
            $map = [['type','=',strtolower($data['dicttype'])],['clinic_id','=',$this->admin['clinic_id']]];
            $info = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_dictsheet')->where($map)->order('id desc')->find();
            if(!$info)
            {
                //若未设置，设置一条默认记录
                $rid = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_dictsheet')->insertGetId([
                    'type' => strtolower($data['dicttype']),
                    'clinic_id' => $this->admin['clinic_id'],
                    'name' => _getDictNameTxt(strtolower($data['dicttype']),ClinicDict::getClinicYeWuDictList()),
                    'status' => '1', //状态1.启用,0停用
                    'create_time' => time(),
                ]);
                if(!$rid)
                {
                    return json(['err' => '2', 'msg' => '默认数据设置错误']);
                }
                $extJson = [];
            }else{
                $extJson = !$info['ext_json'] ? [] : json_decode($info['ext_json'],true);
            }
            //注射单来源列表
            $zsdlyList = ClinicDict::getZhuSheDanLaiYuanList();
            $leftArr = $rightArr = [];
            foreach ($zsdlyList as $key => $val) {
                $disabled = $checked = '';
                foreach ($extJson as $kb => $vb) {
                    if($vb['value'] == $val['id'])
                    {
                        $checked = 'checked';
                        $rightArr[] = $vb['value'];
                        continue;
                    }
                }
                //重新设置值
                $leftArr[] = ['value' => $val['id'], 'title' => $val['name'], 'disabled' => $disabled, 'checked' => $checked];
            }
            unset($info,$extJson,$zsdlyList);
            return json(['err' => '0', 'msg' => '加载成功', 'data_left' => $leftArr, 'data_right' => $rightArr]);
        }catch (\think\Exception $e){ // use think\Exception;
           return json(['err' => '500', 'msg' => '错误：' . $e->getMessage()]);
        }
    }
    //保存诊所已设置的注射单来源
    public function save_clinic_zsdly()
    {
        if(!$this->request->isAjax())
        {
            return json(['err' => '1', 'msg' => '对不起，您的访问方式有误']);
        }
        try
        {
            $data = $this->request->only(['dicttype','json'],'post');
            if(!isset($data['dicttype']) || $data['dicttype'] != 'zsdly')
            {
                return json(['err' => '2', 'msg' => '参数错误，无法执行']);
            }
            $extJson = '';
            $map = [['type','=',strtolower($data['dicttype'])],['clinic_id','=',$this->admin['clinic_id']]];
            if(isset($data['json']))
            {
                if(count($data['json']) > 0)
                {
                    foreach ($data['json'] as $kb => $vb) {
                        $vb['checked'] = '';
                        $vb['disabled'] = '';
                    }
                    $extJson = json_encode($data['json'],JSON_UNESCAPED_UNICODE);
                }
            }
            $editRes = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_dictsheet')->where($map)->update(['ext_json' => $extJson]);
            if(!$editRes) return json(['err' => '3', 'msg' => '数据保存失败']);
            return json(['err' => '0', 'msg' => '数据已保存成功']);
        }catch (\think\Exception $e){ // use think\Exception;
           return json(['err' => '500', 'msg' => '错误：' . $e->getMessage()]);
        }
    }  

}
